package com.google.project.client.Operator;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.project.client.ProjectManager.PMEntrypoint;
import com.google.project.client.Service.DailyReportDetailService;
import com.google.project.client.Service.DailyReportDetailServiceAsync;
import com.google.project.client.Service.ProjTaskService;
import com.google.project.client.Service.ProjTaskServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.DailyReportDetailDTO;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectTaskDTO;

public class OPTProjectTaskDetail extends Composite {

	private static final Binder binder = GWT.create(Binder.class);

	interface Binder extends UiBinder<Widget, OPTProjectTaskDetail> {
	}
	@UiField TextArea txtDescription;
	@UiField Label lblTaskName;
	@UiField Label lblParentName;
	@UiField Label lblStartDate;
	@UiField Label lblDuedate;
	@UiField Label lblWeight;
	@UiField Label lblSubcontructor;
	@UiField Label lblOperator;
	@UiField Label lblAmountOfWork;
	@UiField Label lblFinishedWork;
	@UiField Label lblProject;
	@UiField Button button;
	@UiField DateBox dbFromDate;
	@UiField DateBox dbToDate;
	@UiField  ListBox cboTypeStatistic;
	@UiField Button button_1;
	@UiField Button button_2;
	@UiField Button btnTaskStaff;
	@UiField Label lblEndDate;

	//_____________________________Common variable_____________________________
	private List<ProjectTaskDTO> listTask = new ArrayList<ProjectTaskDTO>();

	private final ProjectServiceAsync projectService = GWT.create(ProjectService.class);
	private final ProjTaskServiceAsync projectTaskService = GWT.create(ProjTaskService.class);
	
	private final DailyReportDetailServiceAsync dailyReportDetailService = GWT.create(DailyReportDetailService.class);
	
	private ProjectTaskDTO currTask  = new ProjectTaskDTO();
	private ProjectDTO currProject  = new ProjectDTO();
	
	//End__________________________Common variable_____________________________
	
	//________________________________Contructor_______________________________
	public OPTProjectTaskDetail() {
		initWidget(binder.createAndBindUi(this));
		dbFromDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		dbToDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
	}
	
	public OPTProjectTaskDetail(ProjectTaskDTO task) {
		currTask= task;
		initWidget(binder.createAndBindUi(this));
		dbFromDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		dbToDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		displayData();
	}
	//End_____________________________Contructor_______________________________
	

//_____________________________Common function_____________________________
	
	public void displayData()
	{
		cboTypeStatistic.addItem("khối lượng ngày","0");
		cboTypeStatistic.addItem("Tổng khối lượng","1");
		lblAmountOfWork.setText(currTask.getAmountOfWork() + " " +currTask.getUnit());
		lblTaskName.setText(currTask.getTaskName());
		Date dueDate = new Date(currTask.getDueDate()) ;
		lblDuedate.setText(CommonFuntion.convertToDate(dueDate));
		Date startDate = new Date(currTask.getStartDate()) ;
		lblStartDate.setText(CommonFuntion.convertToDate(startDate));
		
		if(currTask.getStatus()==2||currTask.getStatus()==3)
		{
		lblEndDate.setText(CommonFuntion.convertToDate(new Date(currProject.getFinishDate())));
		}
		else
		{
			lblEndDate.setText("");
		}
		Double com =CommonFuntion.fomatNumber(currTask.getFinishedWork()*100/currTask.getAmountOfWork());
		lblFinishedWork.setText(CommonFuntion.fomatNumber(currTask.getFinishedWork()) +" " + currTask.getUnit()+" ( "+com+"% )");
		
		if(!currTask.getOptAccountName().equals("0"))
		{
		lblOperator.setText(currTask.getOptAccountName());
		}
		lblWeight.setText(currTask.getWeight() + " %");
		lblSubcontructor.setText(currTask.getSubContructor());
		if (currTask.getParentId() != 0) {
			projectTaskService.getTaskByTaskId(currTask.getParentId(),
					new AsyncCallback<ProjectTaskDTO>() {

						@Override
						public void onSuccess(ProjectTaskDTO result) {
							// TODO Auto-generated method stub
							lblParentName.setText(result.getTaskName());
						}

						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub

						}
					});
		}
	
			
		projectService.getProjectById(currTask.getProjectId(), new AsyncCallback<ProjectDTO>() {
			
			@Override
			public void onSuccess(ProjectDTO result) {
				// TODO Auto-generated method stub
				lblProject.setText("Dự án : "+result.getProjectName());
				currProject = result;
			}
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	private native void drawLine(String datax,String realData,String planData,String unit,int isParent)
    /*-{
    
    if(isParent==1)
    {
    	 $wnd.drawLine(datax,realData,planData,"%");
    }else
    {
    	 $wnd.drawLine(datax,realData,planData,unit);
    }
    }-*/;
	
	Long removeTime(Date date)
	{
		int houseTime =date.getHours()*60 * 60 * 1000;
		int minusTime =date.getMinutes()*60  * 1000;
	    int secTime = date.getSeconds()*1000;
	    Long time = (date.getTime()/1000);
	    Long mili = date.getTime() - 1000*time.intValue();
	   
	    Long newDate = date.getTime()-houseTime - minusTime-secTime-mili.intValue();
	   // Window.alert(date.getTime()+"  "+ newDate+"^_^" +mili);
	    
		return newDate;
	}
	Long removeTime2(Date date)
	{
	String data = (date.getMonth()+1)+"/"+date.getDate()+"/"+(date.getYear()+1990);
	  Date newDate = new Date(data);
		return newDate.getTime();
	}
	Double getValueForDate(Long date,List<DailyReportDetailDTO> data)
	{
		for(DailyReportDetailDTO report:data)
		{
			Date reportDate= new Date( report.getCreatedOnDate());
			
			String compareDate =CommonFuntion.convertToDate( new Date(date)	);
			
			String  reportDateNoTime= CommonFuntion.convertToDate(reportDate);
			if(compareDate.equals(reportDateNoTime))
			{
				return report.getWorkToFinished();
			}
		}
		return 0d;
	}
	//End__________________________Common function_____________________________
	
	//___________________________________Event_________________________________
	//End________________________________Event_________________________________
	

	//_____________________________Common variable_____________________________
	//End__________________________Common variable_____________________________
	//________________________________Contructor_______________________________
	//End_____________________________Contructor_______________________________
	//_____________________________Common function_____________________________
	//End__________________________Common function_____________________________
	
	//___________________________________Event_________________________________
	//End________________________________Event_________________________________
	
Boolean checkTime()
{
    if(dbFromDate.getValue()==null)
    {
    	Window.alert("Từ ngày  không đúng định dạng ");
    	Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	dbFromDate.setFocus(true);
	        }
	    });
    	return false;
    }
    if(dbToDate.getValue()==null)
    {
    	Window.alert("Tới ngày không đúng định dạng ");
    	Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	dbToDate.setFocus(true);
	        }
	    });
    	return false;
    }
    
    if(CommonFuntion.removeTime(dbFromDate.getValue())>CommonFuntion.removeTime(dbToDate.getValue()))
    {
    	Window.alert("Từ ngày không thể lớn hơn tới ngày");
    	Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	dbToDate.setFocus(true);
	        }
	    });
    	return false;
    }
	return true;
	}
	@UiHandler("button")
	void onButtonClick(ClickEvent event) {
		
		if(checkTime())
		{
			 final List<Long> listUpdateTime = new ArrayList<Long>();
			 final List<Long> listUpdateTime2 = new ArrayList<Long>();
			 Date taskFromDate = new Date(currTask.getStartDate());
			 Date taskDueDate = new Date(currTask.getDueDate());
			 if(removeTime(dbFromDate.getValue())<removeTime(taskFromDate)||removeTime(dbToDate.getValue())>removeTime(taskDueDate))
			 {
				 Window.alert("Từ ngày -tới ngày không được nằm ngoài khoảng thời gian triển khai của công việc ");
			 }
			 else
			 {
			Date fromDate = new Date(removeTime(dbFromDate.getValue()));
			Date toDate = new Date(removeTime(dbToDate.getValue()));
			
			
			
			Date viewDate = toDate;
			Long dateDiff = (toDate.getTime() - fromDate.getTime()) / (24 * 60 * 60 * 1000);
			 if(dateDiff >30)
			 {
				 Window.alert("Thời gian thống kê không được vượt quá 30 ngày ");
			 }
			 else
			 {
				  for (int i = 0; i <= dateDiff.intValue(); i++) {
		               listUpdateTime.add(viewDate.getTime());
		               viewDate.setTime(viewDate.getTime() - 24 * 60 * 60 * 1000);
		           }
				   String dataX ="";
				   //lay dataX
				   for(int i =listUpdateTime.size()-1;i>=0;i--)
				   {
						Date dateData = new Date(listUpdateTime.get(i));
						if (dataX.equals("")) {

							dataX = dateData.getDate() + "-"
									+ (dateData.getMonth() + 1);
						} else {
							dataX += "," + dateData.getDate() + "-"
									+ (dateData.getMonth() + 1);
						}
					   listUpdateTime2.add(listUpdateTime.get(i));
				   }
				   final String dataX2=dataX;
				   projectTaskService.getDataForHightChart(currTask, listUpdateTime2, new AsyncCallback<List<Double>>() {
					
					@Override
					public void onSuccess(List<Double> result) {
						// TODO Auto-generated method stub
						String realData ="";
						String planData="";
						//lay du lieu plan data
						Long planStart = removeTime(new Date(currTask.getStartDate()));
						Long planDue = removeTime(new Date(currTask.getDueDate()));
						Long dateDiff=(planDue-planStart)/(24*60*60*1000);
						Long datediffFromBegin= (removeTime(dbFromDate.getValue())-planStart)/(24*60*60*1000);;
					    Double planPerDay = currTask.getAmountOfWork()/(dateDiff+1);
						if(currTask.getGroup()==1)
						{
							planPerDay=100d/(dateDiff+1);
						}
						
						Double pre =0d;
						//int i =1;
						for(int i=0;i<listUpdateTime2.size();i++)
						{
							if (cboTypeStatistic.getValue(cboTypeStatistic.getSelectedIndex()).equals("0")) {
								if(result.size()==0)
								{
									if (realData.equals("")) {
										
										
										realData+=0.00;
									} else {
										realData+=","+0.00;
									}
								}
								else
								{
									if (realData.equals("")) {
										
										
										realData+=result.get(i);
									} else {
										realData+=","+result.get(i);
									}
								}
								
								//lay du lieu plan
								if (planData.equals("")) {
									planData += planPerDay;
								} else {
									planData += "," + planPerDay;
								}
							} else {
								if(result.size()==0)
								{
									if (realData.equals("")) {
										
										
										realData+=0.00;
									} else {
										realData+=","+0.00;
									}
								}else
								{
									if (realData.equals("")) {
										pre = result.get(i);
										realData =""+pre;
									} else {
										pre += result.get(i);
										realData += ","+ pre;
									}
								}
								
								
								if (planData.equals("")) {
									planData += planPerDay*(datediffFromBegin + i+1);
								} else {
									planData += "," + planPerDay*(datediffFromBegin + i+1);
								}
							}
					
						}
						
						drawLine(dataX2,realData,planData,currTask.getUnit(),currTask.getGroup());
						
					}
					
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}
				});
				 } 
			 }
			
		}
	
	}

//	@UiHandler("btnStartTask")
//	void onBtnStartTaskClick(ClickEvent event) {
//		projectTaskService.startWork(currTask, new AsyncCallback<Void>() {
//			
//			@Override
//			public void onSuccess(Void result) {
//				// TODO Auto-generated method stub
//				Window.alert("Công việc đã được kích hoạt thành công");
//			}
//			
//			@Override
//			public void onFailure(Throwable caught) {
//				// TODO Auto-generated method stub
//				
//			}
//		});
//	}
//	@UiHandler("button_1")
//	void onButton_1Click(ClickEvent event) {
//		PMEntrypoint.get().PMProjectDetail(currProject.getProjectID());
//	}
//	@UiHandler("button_2")
//	void onButton_2Click(ClickEvent event) {
//		PMEntrypoint.get().PMProjectTaskStep2(currTask, currProject.getProjectID(),1);
//	}
	@UiHandler("button_1")
	void onButton_1Click(ClickEvent event) {
		OPTEntrypoint.get().OPTTaskConstrain(currTask,currProject.getProjectID(),0);
	}
	//tai lieu cong viec
	@UiHandler("button_2")
	void onButton_2Click(ClickEvent event) {
		OPTEntrypoint.get().DocumentList(currTask.getId(),"2",currProject.getProjectName(),currTask.getTaskName(),3);
	}
	@UiHandler("btnTaskStaff")
	void onBtnTaskStaffClick(ClickEvent event) {
		OPTEntrypoint.get().OPTProjectTaskStaff(currTask,currProject);
	}
}
